<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2>登录</h2>
      </template>
      
      <el-form 
        :model="loginForm" 
        :rules="rules"
        ref="loginFormRef"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username"
            placeholder="用户名"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleLogin" 
            :loading="loading" 
            class="login-button"
          >
            登录
          </el-button>
        </el-form-item>

        <div class="register-link">
          还没有账号？
          <router-link to="/register">立即注册</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
import axios from 'axios'

const store = useStore()
const router = useRouter()
const loginFormRef = ref<FormInstance>()
const loading = ref(false)

const loginForm = ref({
  username: '',
  password: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return

  await loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const response = await axios.post('/login', {
          username: loginForm.value.username,
          password: loginForm.value.password
        })

        console.log('Login response:', response.data)

        if (response.data.token) {
          store.commit('setToken', response.data.token)
          
          const userData = {
            id: response.data.user.id,
            username: response.data.user.username,
            role: response.data.user.role,
            avatar: response.data.user.avatar || '/default-avatar.png',
          }

          store.commit('setUserInfo', userData)
          localStorage.setItem('user', JSON.stringify(userData))

          ElMessage.success('登录成功')
          
          if (userData.role === 'admin') {
            router.push('/admin/orders')
          } else {
            router.push('/')
          }
        }
      } catch (error) {
        console.error('Login error:', error)
        ElMessage.error(error.response?.data?.error || '登录失败')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
}

.login-button {
  width: 100%;
}

.register-link {
  text-align: center;
  margin-top: 16px;
  font-size: 14px;
}

:deep(.el-card__header) {
  text-align: center;
  padding: 15px;
}

h2 {
  margin: 0;
}
</style> 